/**
 * AI功能测试面板
 * 用于测试AI服务的各项功能
 */

import React, { useState } from 'react'
import { Card, Button, Input, Space, Alert, Divider, Typography, message } from 'antd'
import { RobotOutlined, SettingOutlined } from '@ant-design/icons'
import { useAIAssistant } from '../../hooks/useAIAssistant'
import { AISettingsModal } from '../../components/AISettings'
import { hasAPIKey } from '../../../services/ai'

const { TextArea } = Input
const { Title, Text } = Typography

export const AITestPanel: React.FC = () => {
  const [context, setContext] = useState('在一个阳光明媚的早晨，小明走在去学校的路上。他')
  const [generatedText, setGeneratedText] = useState('')
  const [showSettings, setShowSettings] = useState(false)

  const { isGenerating, error, continueWriting, clearError, reloadConfig, hasConfig } = useAIAssistant()

  const handleTest = async () => {
    console.log('[AI测试] 开始测试AI续写')

    const result = await continueWriting({
      fullText: context,
      cursorPosition: context.length
    })

    if (result) {
      setGeneratedText(result)
      console.log('[AI测试] 生成成功', result)
    }
  }

  const handleSettingsSaved = () => {
    setShowSettings(false)
    reloadConfig()
    message.success('配置已更新')
  }

  return (
    <div style={{ padding: 24 }}>
      <Title level={3}>AI功能测试</Title>

      {/* API密钥状态 */}
      <Card style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text>
              API密钥状态: {' '}
              {hasAPIKey() ? (
                <Text type="success">已配置</Text>
              ) : (
                <Text type="danger">未配置</Text>
              )}
            </Text>
            <Button
              icon={<SettingOutlined />}
              onClick={() => setShowSettings(true)}
            >
              配置AI设置
            </Button>
          </div>

          {!hasAPIKey() && (
            <Alert
              message="请先配置OpenAI API密钥"
              description="点击右侧按钮打开设置面板，输入您的API密钥"
              type="warning"
              showIcon
            />
          )}
        </Space>
      </Card>

      {/* 测试区域 */}
      <Card title="AI续写测试">
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <div>
            <Text strong>输入上下文：</Text>
            <TextArea
              value={context}
              onChange={(e) => setContext(e.target.value)}
              placeholder="输入一段文字，AI将根据上下文续写..."
              rows={6}
              style={{ marginTop: 8 }}
            />
          </div>

          <Button
            type="primary"
            icon={<RobotOutlined />}
            onClick={handleTest}
            loading={isGenerating}
            disabled={!hasConfig}
            block
          >
            {isGenerating ? '生成中...' : 'AI续写'}
          </Button>

          {error && (
            <Alert
              message="AI生成失败"
              description={error.message}
              type="error"
              showIcon
              closable
              onClose={clearError}
            />
          )}

          {generatedText && (
            <div>
              <Divider />
              <Text strong>AI生成内容：</Text>
              <div
                style={{
                  marginTop: 8,
                  padding: 16,
                  background: '#f5f5f5',
                  borderRadius: 4,
                  whiteSpace: 'pre-wrap'
                }}
              >
                {generatedText}
              </div>
            </div>
          )}
        </Space>
      </Card>

      {/* 测试说明 */}
      <Card title="测试说明" style={{ marginTop: 16 }}>
        <Space direction="vertical">
          <Text>1. 首先配置OpenAI API密钥（点击上方"配置AI设置"按钮）</Text>
          <Text>2. 在输入框中输入一段文字作为上下文</Text>
          <Text>3. 点击"AI续写"按钮，AI将根据上下文生成续写内容</Text>
          <Text>4. 查看控制台日志了解详细的执行过程</Text>
          <Divider />
          <Text type="secondary">默认上下文: "在一个阳光明媚的早晨，小明走在去学校的路上。他"</Text>
        </Space>
      </Card>

      {/* AI设置弹窗 */}
      <AISettingsModal
        visible={showSettings}
        onClose={handleSettingsSaved}
      />
    </div>
  )
}
